// alliance//allianceManager/index.js
const app = getApp();
const utils = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tagindex: 1, //1联盟管理2加入联盟3联盟卡包4联盟商家
    isCreate: false, //创建联盟权限
    addPage: false, //是否点击了创建联盟悬浮按钮
    CurrentPage: 1, //联盟商家
    loadingMoreHidden: 1,
    CurrentPageAlliance: 1, //联盟列表
    loadingMoreHiddenAlliance: 1,
    allianceName: '', //联盟名称
    totalCount: '', //卡包总数
    singleCount: '', //单个商家卡包数量
    storeCount: '', //商家总数
    isAuthorize: 0,//0不使用联盟授权码，1使用联盟授权码
    showDissolve: false, //解散联盟规则
    showIndex: true, //首次进来该页面显示联盟列表
    showAllianceCode: false, //是否显示联盟码
    allianceList: [], //创建的所有联盟
    staffid: 0, //名片id
    id: 0, //联盟id
    isLeader: false, //是否盟主
    addedList: [], //加入联盟页：我加入的联盟或向我发出邀请的联盟
    applyList: [],
    allianceid: 0, //盟主想要管理的联盟id
    allianceTotalcount: 0,
    isSelectCard: 1, //1联盟特权会员卡，2联盟特权优惠券
    projectListAlliance: [], //联盟商家项目卡
    cardAlliance: {}, //联盟商家会员卡
    couponListAlliance: [], //联盟商家优惠券
    showRuler: false,
    windowWidth: 314, //画布宽度
    canvsaHeight: 450,
    myTotalCount: 0,
    showNumber: false, //盟主修改数量弹窗
    leaderSingleCount: '',
    applyidLeader: 0, //修改某盟友的数量
    shareimgpath: '', // 分享小图临时路径
    cardInfo: {},
    alpha: '',
    addBg: false,
    windowHeight: '',
    allianmerlist: [], //联盟商家
    keyword: "",
    classList: [],
    storeiid: 0,
    showAuthCode: false,//是否显示授权码
    authcodeList: [],
  },
  tapClassSelect: function (e) {
    let cid = e.currentTarget.dataset.cid;
    this.setData({
      storeiid: cid
    })
    this.getAllianceStaffList(this.data.allianceid);
  },

  // 获取店铺行业
  getIndustryList: function () {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/store/GetIndustryList?storeId=' + app.globalData.storeId,
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            classList: res.data.Data
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },
  // 是否有创建联盟权限
  getManageOption: function () {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Alliance/GetManageOption?uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          let tagindex = that.data.tagindex;
          if (!res.data.Data.IsCreate && tagindex == 1) {
            tagindex = 2;
          }
          that.setData({
            isCreate: res.data.Data.IsCreate,
            tagindex: tagindex
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },
  // 我创建的联盟
  getAllianceList: function () {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Alliance/GetAllianceList?uid=' + app.globalData.userInfo.Uid + '&page=' + that.data.CurrentPageAlliance,
      success: function (res) {
        if (res.data.Code == 0) {
          let allianceList = res.data.Data.Items;
          if (that.data.CurrentPageAlliance != 1) {
            var preGoods = that.data.allianceList;
            allianceList = preGoods.concat(allianceList);
          }
          that.setData({
            allianceList: allianceList,
            loadingMoreHiddenAlliance: res.data.Data.TotalPages
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  //是否需要授权码
  isAuthor: function (e) {
    let isauth = e.currentTarget.dataset.isauth;
    this.setData({
      isAuthorize: isauth
    })
  },
  // 创建联盟
  addAlliance: function () {
    let that = this;
    let id = that.data.id;
    let name = that.data.allianceName;
    let totalCount = that.data.totalCount;
    let singleCount = that.data.singleCount;
    let storeCount = that.data.storeCount;
    let isAuthorize = that.data.isAuthorize;
    if (id > 0) { //编辑
      let list = that.data.allianceList;
      for (let i = 0; i < list.length; i++) {
        if (list[i].Id == id) {
          name = list[i].Name;
          totalCount = list[i].TotalCount;
          singleCount = list[i].SingleCount;
          storeCount = list[i].StoreCount;
        }
      }
    }
    if (name == '' || totalCount == '' || singleCount == '' || storeCount == '') {
      wx.showModal({
        title: '提示',
        content: '填写所有信息之后才能提交',
        showCancel: false
      })
      return;
    }
    wx.showLoading({
      title: '提交中...',
      mask: true
    })
    wx.request({
      url: app.globalData.host + '/api/Alliance/AddUpdateAlliance',
      method: 'POST',
      data: {
        Id: id,
        Uid: app.globalData.userInfo.Uid,
        Name: name,
        TotalCount: totalCount,
        SingleCount: singleCount,
        StoreCount: storeCount,
        IsAuth: isAuthorize
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          if (id > 0) {
            wx.showToast({
              title: '修改成功',
              duration: 2000
            })
          } else {
            wx.showToast({
              title: '创建成功',
              duration: 2000
            })
          }
          that.getAllianceList();
          that.setData({
            addPage: false,
            showIndex: true
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },
  //修改联盟
  updateAlliance: function (e) {
    let that = this;
    let id = e.currentTarget.dataset.id;
    let allianceList = that.data.allianceList;
    for (let i = 0; i < allianceList.length; i++) {
      if (allianceList[i].Id == id) {
        that.setData({
          id: id
        })
        that.addAlliance();
      }
    }
  },
  //是否需要授权码(盟主管理)
  isAuthorManage: function (e) {
    let isauth = e.currentTarget.dataset.isauth;
    this.setData({
      isAuthorize: isauth
    })
    let id = e.currentTarget.dataset.id;
    let allianceList = this.data.allianceList;
    for (let i = 0; i < allianceList.length; i++) {
      if (allianceList[i].Id == id) {
        this.setData({
          id: id
        })
        this.addAlliance();
      }
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    that.getIndustryList();
    that.getShareImgData();
    that.getStaffInfo();
    that.getManageOption();
    that.getAllianceList();
    that.getListByAlliance();
    wx.hideShareMenu(); //隐藏右上角转发按钮；
    if (options.tagindex) {
      that.setData({
        tagindex: options.tagindex
      })
      if (options.tagindex == 3) {
        setTimeout(function () {
          that.getMyAlliancePackage();
        }, 500);
      }
    }
    try {
      var res = wx.getSystemInfoSync();
      //每一个字母所占的高度
      that.apHeight = (res.windowHeight - 100) / 28;
      that.setData({
        windowHeight: res.windowHeight
      })
    } catch (e) { }
  },

  // 联盟数据
  toAllianceData: function (e) {
    let allianceId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../allianceData/index?allianceId=' + allianceId,
    })
  },

  // 以下几个方法与搜索相关
  handleInput: function (e) {
    this.data.keyword = e.detail.value;
  },
  handleBlur: function (e) {
    this.data.keyword = e.detail.value;
  },
  handleConfirm: function (e) {
    this.data.keyword = e.detail.value;
    let list = this.data.addedList;
    if (list.length > 0) {
      this.getAllianceStaffList(list[0].Id);
    }
  },
  handleSearchWord: function () {
    let addedList = this.data.addedList;
    if (addedList.length > 0) {
      this.getAllianceStaffList(addedList[0].Id);
    }
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  getStaffInfo: function () {
    let that = this;
    let cardId = wx.getStorageSync('cardId');
    if (!cardId) {
      cardId = 0;
    }
    wx.request({
      url: app.globalData.host + '/api/Staff/GetInfo?id=' + cardId,
      success: function (res) {
        if (res.data.Code == 0) {
          that.data.cardInfo = res.data.Data;
        } else {
          wx.showToast({
            title: '信息获取失败',
            duration: 500
          })
        }
      }
    })
  },
  // 切换tab
  changeTag: function (e) {
    let tagindex = e.currentTarget.dataset.tagindex;
    this.setData({
      tagindex: tagindex
    })
    if (tagindex == 1) {
      this.getManageOption();
      this.getAllianceList();
    }
    if (tagindex == 2) {
      this.getListByAlliance();
    }
    if (tagindex == 3) {
      let list = this.data.addedList;
      if (list.length > 0) {
        this.getMyAlliancePackage();
      }
    }
    if (tagindex == 4) {
      let list = this.data.addedList;
      let allianmerlist = [];
      if (list.length > 0) {
        this.setData({
          allianceid: list[0].Id,
          allianmerlist: allianmerlist,
          CurrentPage: 1
        })
        this.getLocation();
      }
      this.setData({
        isLeader: false
      })
    }
  },
  toAddAlliance: function () {
    this.setData({
      addPage: true,
      showIndex: false,
      id: 0,
      isAuthorize: 0
    })
  },

  showDissolve: function () {
    let that = this;
    that.setData({
      showDissolve: !that.data.showDissolve
    })
  },

  // 邀请商家加盟
  toInvite: function (e) {
    let allianceId = e.currentTarget.dataset.allianceid;
    wx.navigateTo({
      url: '../merchantList/index?allianceId=' + allianceId,
    })
  },

  // 显示联盟码
  showAllianceCode: function (e) {
    let windowWidth = wx.getSystemInfoSync().windowWidth * 314 / 375;
    let canvsaHeight = windowWidth * 450 / 314;
    let qrCode = 'https://static.711688.net.cn/upload/alliance/' + e.currentTarget.dataset.qrcode;
    let allianceName = e.currentTarget.dataset.alliancename;
    this.setData({
      showAllianceCode: !this.data.showAllianceCode,
      windowWidth: windowWidth,
      canvsaHeight: canvsaHeight
    })
    this.getAiCardInfo(qrCode, allianceName);
  },

  closeAllianceCode: function () {
    this.setData({
      showAllianceCode: !this.data.showAllianceCode
    })
  },

  //解散联盟
  dissolve: function (e) {
    let that = this;
    let allianceid = e.currentTarget.dataset.allianceid;
    wx.showModal({
      title: '提示',
      content: '您确定要解散联盟吗？',
      success(res) {
        if (res.confirm) {
          wx.request({
            url: app.globalData.host + '/api/Alliance/SetAllianceState?id=' + allianceid + '&uid=' + app.globalData.userInfo.Uid + '&state=2',
            success: function (res) {
              if (res.data.Code == 0) {
                wx.showToast({
                  title: '解散成功',
                  duration: 2000,
                  mask: true
                })
                that.getAllianceList();
              } else {
                wx.showModal({
                  title: '提示',
                  content: res.data.Message,
                  showCancel: false
                })
              }
            }
          })
        }
      }
    })
  },

  getShareImgData: function () {
    this.painter('share-canvas-id', {
      bg_url: 'https://static.711688.net.cn/upload/card/source/ua_2005131103020634897.jpg',
    })
      .then(data => {
        this.data.shareimgpath = data;
      })
      .catch(err => { })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    let that = this;
    let allianceid = res.target.dataset.allianceid;
    let name = res.target.dataset.alliancename;
    let cardInfo = that.data.cardInfo;
    let cardid = wx.getStorageSync('cardId');
    return {
      imageUrl: that.data.shareimgpath,
      title: name + '的' + cardInfo.Name + '给你专属的联盟礼包，点击领取',
      path: '/merchant/alliance/receiveAllianceCoupon/index?id=' + cardid + '&allianceid=' + allianceid + '&source=5&shareUid=' + cardInfo.Uid,
      success: function (res) {
        wx.showModal({
          title: '提示',
          content: '转发成功',
          showCancel: false
        })
      }
    }
  },

  // 取消创建联盟
  cancelAdd: function () {
    this.setData({
      showIndex: true,
      addPage: false
    })
  },

  getAiCardInfo: function (qrcode, name) {
    let that = this;
    let userid = app.globalData.userInfo.Uid;
    utils.getCardId(userid, function (cardid) {
      wx.request({
        url: app.globalData.host + '/api/Staff/GetInfo?id=' + cardid,
        success: function (res) {
          let cardInfo = res.data.Data;
          that.getCanvasimg(qrcode, name, cardInfo);
        }
      })
    })
  },
  // 名称
  bindAllianceName: function (e) {
    this.setData({
      allianceName: e.detail.value
    })
  },
  // 卡包总数量
  bindAllianceSum: function (e) {
    this.setData({
      totalCount: e.detail.value
    })
  },
  // 单商家卡包数量
  bindCouponCount: function (e) {
    this.setData({
      singleCount: e.detail.value
    })
  },
  //总商家数量
  bindBusCount: function (e) {
    this.setData({
      storeCount: e.detail.value
    })
  },
  // 修改某个联盟名称
  binditemName: function (e) {
    let that = this;
    let list = that.data.allianceList;
    let id = e.currentTarget.dataset.id;
    for (let i = 0; i < list.length; i++) {
      if (list[i].Id == id) {
        list[i].Name = e.detail.value;
      }
    }
    that.setData({
      allianceList: list
    })
  },
  // 修改某个联盟卡包总数量
  binditemSum: function (e) {
    let that = this;
    let list = that.data.allianceList;
    let id = e.currentTarget.dataset.id;
    for (let i = 0; i < list.length; i++) {
      if (list[i].Id == id) {
        list[i].TotalCount = e.detail.value;
        break;
      }
    }
    that.setData({
      allianceList: list
    })
  },
  // 修改某个联盟单商家卡包数量
  binditemCount: function (e) {
    let that = this;
    let list = that.data.allianceList;
    let id = e.currentTarget.dataset.id;
    for (let i = 0; i < list.length; i++) {
      if (list[i].Id == id) {
        list[i].SingleCount = e.detail.value;
        break;
      }
    }
    that.setData({
      allianceList: list
    })
  },
  // 加入者修改卡包总数量
  bindMyTotaoCount: function (e) {
    this.data.myTotalCount = e.detail.value;
  },

  // 加入联盟页面所有操作
  // 获取我加入的联盟或被邀请的联盟
  getListByAlliance: function () {
    let that = this;
    let myTotalCount = that.data.myTotalCount;
    wx.request({
      url: app.globalData.host + '/api/Alliance/GetAllianceListByApply?uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          let addedList = res.data.Data.AllianceList;
          let applyList = res.data.Data.ApplyList;
          let allianceId = 0;
          if (addedList.length > 0) {
            allianceId = addedList[0].Id;
            myTotalCount = addedList[0].TotalCount;
          }
          that.setData({
            addedList: addedList,
            allianceid: allianceId,
            applyList: applyList,
          })
          that.data.myTotalCount = myTotalCount;
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },
  //加入联盟
  setApplyState: function (e) {
    let that = this;
    let state = e.currentTarget.dataset.state;
    let applyid = e.currentTarget.dataset.applyid;
    let isleaderop = e.currentTarget.dataset.isleaderop;
    let marked = '';
    if (state == 1) {
      marked = '是否加入联盟';
    }
    if (state == 2) {
      marked = '是否拒绝加入联盟';
    }
    if (state == 3) {
      marked = '是否退出联盟';
    }
    wx.showModal({
      title: '提示',
      content: marked,
      success(res) {
        if (res.confirm) {
          wx.request({
            url: app.globalData.host + '/api/Alliance/SetApplyState?applyId=' + applyid + '&uid=' + app.globalData.userInfo.Uid + '&state=' + state,
            success: function (res) {
              let content = '';
              if (state == 1) {
                content = '加入联盟成功';
              }
              if (state == 2) {
                content = '您已拒绝加入联盟';
              }
              if (state == 3) {
                content = '退出联盟成功';
              }
              if (res.data.Code == 0) {
                wx.showToast({
                  icon: 'none',
                  title: content,
                  duration: 2000,
                  mask: true
                })
                if (isleaderop == 1) {
                  let list = that.data.addedList;
                  if (list.length > 0) {
                    this.getAllianceInfo(list[0].Id);
                    this.getAllianceStaffList(list[0].Id);
                  }
                } else {
                  that.getListByAlliance();
                  if (state == 3) {
                    that.setData({
                      projectListAlliance: [],
                      cardAlliance: {},
                      couponListAlliance: []
                    })
                  }
                }
              } else {
                wx.showModal({
                  title: '提示',
                  content: res.data.Message,
                  showCancel: false
                })
              }
            }
          })
        }
      }
    })
  },
  // 获取授权码
  showAuthCode: function (e) {
    let that = this;
    let allianceid = e.currentTarget.dataset.allianceid;
    wx.request({
      url: app.globalData.host + '/api/alliance/GetCodeTopList?allianceId=' + allianceid + '&createUid=' + app.globalData.userInfo.Uid + '&state=1',
      success: function (res) {
        if (res.data.Data.Items.length > 0) {
          let authcodeList = res.data.Data.Items;
          that.setData({
            authcodeList: authcodeList
          })
        }
      }
    })
    that.setData({
      showAuthCode: !that.data.showAuthCode
    })
  },
  // 复制授权码
  copyCode: function (e) {
    let data = e.currentTarget.dataset.code.toString();
    wx.setClipboardData({
      data: data,
      success(res) {
        wx.showToast({
          title: '授权码已复制',
        })
      }
    })
  },
  closeAllianceAuthCode: function () {
    this.setData({
      showAuthCode: !this.data.showAuthCode
    })
  },
  // 申请开通联盟商
  toApplyAlliance: function () {
    wx.navigateTo({
      url: '../applyAlliance/index',
    })
  },
  // 加入者修改联盟卡包数量
  setApplyTotalCount: function (e) {
    let that = this;
    let applyId = e.currentTarget.dataset.id;
    wx.request({
      url: app.globalData.host + '/api/Alliance/SetApplyTotalCount?applyId=' + applyId + '&uid=' + app.globalData.userInfo.Uid + '&totalCount=' + that.data.myTotalCount,
      success: function (res) {
        if (res.data.Code == 0) {
          wx.showToast({
            title: '保存成功',
            duration: 2000,
            mask: true
          })
          that.getListByAlliance();
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  showRuler: function () {
    this.setData({
      showRuler: !this.data.showRuler
    })
  },

  // 联盟卡券已发放数量
  toRecardList: function (e) {
    let allianceId = e.currentTarget.dataset.id;
    let listtype = e.currentTarget.dataset.listtype;
    let createuid = e.currentTarget.dataset.createuid;
    wx.navigateTo({
      url: '/merchant/merchants/sendAndCheckRecords/index?allianceid=' + allianceId + '&listtype=' + listtype + '&createUid=' + createuid,
    })
  },

  // 联盟卡包页面
  changCouponType: function (e) {
    let isSelectCard = e.currentTarget.dataset.isselectcard;
    this.setData({
      isSelectCard: isSelectCard
    })
  },

  // 获取我创建的联盟卡包
  getMyAlliancePackage: function () {
    let that = this;
    let addedList = that.data.addedList;
    // let staffId = wx.getStorageSync("staffid");
    let staffId = wx.getStorageSync("cardId");
    if (addedList.length > 0) {
      if (!staffId) {
        staffId = 0;
      }
      wx.request({
        url: app.globalData.host + '/api/Alliance/GetAlliancePackage?staffId=' + staffId + '&allianceId=' + addedList[0].Id + "&showAll=1",
        success: function (res) {
          if (res.data.Code == 0) {
            let couponList = res.data.Data.CouponTypeList;
            let project = res.data.Data.CardItemList;
            let card = {};
            if (res.data.Data.Card) {
              card = res.data.Data.Card;
              card.Discount = (card.Discount * 0.1).toFixed(1);
              card.EndTime = card.EndTime.substr(0, 10).replace(/-/g, "/");
            } else {
              card.EndTime = res.data.ServerTime.substr(0, 10).replace(/-/g, "/");
              card.Title = "VIP会员卡";
              card.Discount = 10;
              card.CardNo = '0000 0000 0000 0000';
            }
            let date = new Date();
            for (let i = 0; i < couponList.length; i++) {
              var date2 = new Date(Date.parse(couponList[i].sendendtime.replace(/-/g, "/")));
              if (date2 < date) {
                couponList[i].isExpiretime = 1;
              } else {
                couponList[i].isExpiretime = 0;
              }
              couponList[i].sendcount = couponList[i].SendCount;
              couponList[i].sendstarttime = couponList[i].sendstarttime.substr(0, 10);
              couponList[i].sendendtime = couponList[i].sendendtime.substr(0, 10);

            }
            that.setData({
              projectListAlliance: project,
              cardAlliance: card,
              couponListAlliance: couponList
            })
          } else {
            wx.showModal({
              title: '提示',
              content: res.data.Message,
              showCancel: false
            })
          }
        }
      })
    }
  },
  // 创建或修改会员卡
  toAddOrUpdatecard: function (e) {
    let that = this;
    let id = 0;
    let addedList = that.data.addedList;
    let url = '';
    if (addedList.length > 0) {
      if (that.data.cardAlliance.Id) {
        id = that.data.cardAlliance.Id;
        url = '/merchant/merchants/addVipcard/index?id=' + id + '&allianceid=' + addedList[0].Id
      } else {
        url = '/merchant/merchants/addVipcard/index?allianceid=' + addedList[0].Id
      }
      wx.navigateTo({
        url: url
      })
    } else {
      wx.showToast({
        icon: 'none',
        title: '加入联盟之后才能创建联盟卡包',
        duration: 2000,
        mask: true
      })
    }

  },
  //新增卡项目
  toAddProject: function () {
    let that = this;
    let addedList = that.data.addedList;
    if (addedList.length > 0) {
      wx.navigateTo({
        url: '/merchant/share/addProjectShare/index?allianceid=' + addedList[0].Id
      })
    } else {
      wx.showToast({
        icon: 'none',
        title: '加入联盟之后才能创建联盟卡包',
        duration: 2000,
        mask: true
      })
    }
  },
  // 修改卡项目
  updateCardItem: function (e) {
    let that = this;
    let id = e.currentTarget.dataset.id;
    let addedList = that.data.addedList;
    wx.navigateTo({
      url: '/merchant/share/addProjectShare/index?cid=' + id + '&allianceid=' + addedList[0].Id
    })
  },

  // 删除卡项目
  deleteCardItem: function (e) {
    let that = this;
    let id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '确认删除？',
      success(res) {
        if (res.confirm) {
          wx.request({
            url: app.globalData.host + '/api/Coupon/DeleteCardItem?id=' + id + '&uid=' + app.globalData.userInfo.Uid,
            success: function (res) {
              if (res.data.Code == 0) {
                wx.showToast({
                  title: '删除成功',
                  duration: 2000,
                  mask: true
                })
                that.getMyAlliancePackage();
              } else {
                wx.showModal({
                  title: '提示',
                  content: res.data.Message,
                  showCancel: false
                })
              }
            }
          })
        }
      }
    })
  },
  //新增优惠券
  toAddCoupon: function (e) {
    let that = this;
    let type = e.currentTarget.dataset.type;
    let addedList = that.data.addedList;
    if (addedList.length > 0) {
      wx.navigateTo({
        url: '/merchant/merchants/addCoupon/index?type=' + type + '&allianceid=' + addedList[0].Id
      })
    } else {
      wx.showToast({
        icon: 'none',
        title: '加入联盟之后才能创建联盟卡包',
        duration: 2000,
        mask: true
      })
    }
  },
  // 关闭优惠券
  updateCouponState: function (e) {
    let that = this;
    let coupontypeid = e.currentTarget.dataset.coupontypeid;
    let state = e.currentTarget.dataset.state;
    wx.showModal({
      title: '提示',
      content: '作废后不可恢复，是否确认？',
      success(res) {
        if (res.confirm) {
          wx.request({
            url: app.globalData.host + '/api/Coupon/ChangeCouponTypeState?couponTypeId=' + coupontypeid + '&state=' + state,
            success: function (res) {
              if (res.data.Code == 0) {
                if (!state) {
                  wx.showToast({
                    title: '优惠券已关闭',
                    duration: 2000,
                    mask: true
                  })
                }
                that.getMyAlliancePackage();
              } else {
                wx.showModal({
                  title: '提示',
                  content: res.data.Message,
                  showCancel: false
                })
              }
            }
          })
        }
      }
    })
  },
  // 删除优惠券
  deleteCoupon: function (e) {
    let that = this;
    let coupontypeid = e.currentTarget.dataset.coupontypeid;
    wx.showModal({
      title: '提示',
      content: '删除后，已发放的该张优惠券失效，是否操作？',
      success(res) {
        if (res.confirm) {
          wx.request({
            url: app.globalData.host + '/api/Coupon/DeleteCouponType?couponTypeId=' + coupontypeid,
            success: function (res) {
              if (res.data.Code == 0) {
                wx.showToast({
                  title: '删除成功',
                  duration: 1000,
                  mask: true
                })
                that.getMyAlliancePackage();
              } else {
                wx.showModal({
                  title: '提示',
                  content: res.data.Message,
                  showCancel: false
                })
              }
            }
          })
        }
      }
    })
  },

  // 优惠券详情
  toDetail: function (e) {
    let coupontypeid = e.currentTarget.dataset.coupontypeid;
    let isalliance = e.currentTarget.dataset.isalliance;
    let type = e.currentTarget.dataset.type;
    wx.navigateTo({
      url: '/merchant/merchants/addCoupon/index?coupontypeid=' + coupontypeid + '&type=' + type + '&isEditor=1' + "&isalliance=" + isalliance + '&allianceid=' + this.data.addedList[0].Id,
    })
  },

  // 优惠券核销记录
  toUseRecord: function (e) {
    let coupontypeid = e.currentTarget.dataset.coupontypeid;
    let listtype = e.currentTarget.dataset.listtype;
    wx.navigateTo({
      url: '/merchant/merchants/sendAndCheckRecords/index?coupontypeid=' + coupontypeid + '&listtype=' + listtype,
    })
  },

  //获取我所加入的联盟的联盟信息
  getAllianceInfo: function (allianceid) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Alliance/GetAlliance?allianceId=' + allianceid,
      success: function (res) {
        if (res.data.Code == 0) {
          let leader = res.data.Data.Uid
          if (leader == app.globalData.userInfo.Uid) {
            that.setData({
              isLeader: true
            })
          }
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },
  // 获取某联盟的所有商家
  getAllianceStaffList: function (allianceId) {
    let that = this;
    let location = wx.getStorageSync('location');
    let lat = location.lat;
    let log = location.lng;
    if (!lat || !log) {
      lat = 0;
      log = 0;
    }
    wx.request({
      url: app.globalData.host + '/api/Alliance/GetAllianceStaffList?allianceId=' + allianceId + '&nickName=' + that.data.keyword + '&industryId=' + that.data.storeiid + '&page=' + that.data.CurrentPage + '&latitude=' + lat + '&longitude=' + log,
      success: function (res) {
        if (res.data.Code == 0) {
          let addedMerlist = res.data.Data.Items;
          if (that.data.CurrentPage != 1) {
            var preGoods = that.data.allianmerlist;
            addedMerlist = preGoods.concat(addedMerlist);
          }
          if (addedMerlist.length > 0) {
            for (let i = 0; i < addedMerlist.length; i++) {
              addedMerlist[i].Avater = utils.formatAvater(addedMerlist[i].Avater, 'https://static.711688.net.cn/upload/card/source/');
              if (addedMerlist[i].Distance >= 1000) {
                addedMerlist[i].Distances = parseFloat(addedMerlist[i].Distance / 1000).toFixed(2);
              }
              let carditems = addedMerlist[i].CardItemList;
              if (carditems.length > 0) {
                for (let j = 0; j < carditems.length; j++) {
                  var detailpics = carditems[j].DetailPics;
                  carditems[j].showDetailPics = '';
                  var list = [];
                  if (detailpics != '') {
                    var newDetailPics = detailpics.split(",");
                    for (let k = 0; k < newDetailPics.length; k++) {
                      list[k] = 'https://static.711688.net.cn/upload/coupondetail/' + newDetailPics[k];
                    }
                    carditems[j].showDetailPics = list[0];
                  }
                }
              }
              let coupons = addedMerlist[i].CouponTypeList;
              if (coupons.length > 0) {
                for (let j = 0; j < coupons.length; j++) {
                  var detailpics = coupons[j].DetailPics;
                  coupons[j].showDetailPics = '';
                  var list = [];
                  if (detailpics) {
                    var newDetailPics = detailpics.split(",");
                    for (let k = 0; k < newDetailPics.length; k++) {
                      list[k] = 'https://static.711688.net.cn/upload/coupondetail/' + newDetailPics[k];
                    }
                    coupons[j].showDetailPics = list[0];
                  }
                }
              }
              let card = addedMerlist[i].Card;
              if (card) {
                card.Discount = card.Discount * 0.1;
                card.Discount = card.Discount.toFixed(1);
                var detailpics = card.DetailPics;
                if (detailpics) {
                  card.showDetailPics = '';
                  var list = [];
                  if (detailpics != '') {
                    var newDetailPics = detailpics.split(",");
                    for (let k = 0; k < newDetailPics.length; k++) {
                      list[k] = 'https://static.711688.net.cn/upload/coupondetail/' + newDetailPics[k];
                    }
                    card.showDetailPics = list[0];
                  }
                }

              }
            }
          }
          that.setData({
            allianmerlist: addedMerlist,
            loadingMoreHidden: res.data.Data.TotalPages
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },
  // 加载更多(联盟商家列表)
  loadMore: function (e) {
    var that = this;
    if (that.data.loadingMoreHidden > 1 && that.data.CurrentPage < that.data.loadingMoreHidden) {
      var currPage = that.data.CurrentPage;
      that.setData({
        CurrentPage: currPage + 1
      })
      that.getAllianceStaffList(that.data.allianceid);
    } else {
      return
    }
  },
  //加载更多（联盟列表）
  loadMoreAlliance: function () {
    var that = this;
    if (that.data.loadingMoreHiddenAlliance > 1 && that.data.CurrentPageAlliance < that.data.loadingMoreHiddenAlliance) {
      var currPage = that.data.CurrentPageAlliance;
      that.setData({
        CurrentPageAlliance: currPage + 1
      })
      that.getAllianceList();
    } else {
      return;
    }
  },
  // 优惠券详情
  toCouponDetail: function (e) {
    let type = e.currentTarget.dataset.type;
    let coupontypeid = e.currentTarget.dataset.coupontypeid;
    wx.navigateTo({
      url: '/merchant/merchants/cardDetails/index?type=' + type + '&coupontypeid=' + coupontypeid,
    })
  },
  // 消费卡详情
  toCardItemDetail: function (e) {
    let type = e.currentTarget.dataset.type;
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/merchant/merchants/cardDetails/index?type=' + type + '&ids=' + id,
    })
  },
  showNumber: function (e) {
    let applyid = e.currentTarget.dataset.applyid;
    let singlecount = e.currentTarget.dataset.singlecount
    this.setData({
      showNumber: !this.data.showNumber,
      applyidLeader: applyid,
      leaderSingleCount: singlecount
    })
  },
  bindleaderSingleCount: function (e) {
    this.setData({
      leaderSingleCount: e.detail.value
    })
  },
  // 盟主修改商家卡包数量
  setApplySingleCount: function () {
    let that = this;
    let leaderSingleCount = that.data.leaderSingleCount;
    if (!leaderSingleCount) {
      wx.showToast({
        icon: 'none',
        title: '请输入发放数量',
        duration: 2000,
        mask: true
      })
      return;
    }
    if (leaderSingleCount > that.data.allianceTotalcount) {
      wx.showToast({
        icon: 'none',
        title: '商家发放数量不能大于联盟总数量',
        duration: 2000,
        mask: true
      })
      return;
    }
    wx.request({
      url: app.globalData.host + '/api/Alliance/SetApplySingleCount?applyId=' + that.data.applyidLeader + '&createUid=' + app.globalData.userInfo.Uid + '&singleCount=' + leaderSingleCount,
      success: function (res) {
        if (res.data.Code == 0) {
          wx.showToast({
            title: '保存成功',
            mask: true,
            duration: 1000
          })
          that.setData({
            showNumber: !that.data.showNumber
          })
          that.getAllianceStaffList(that.data.allianceid);
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  closeShowNumber: function () {
    this.setData({
      showNumber: !this.data.showNumber
    })
  },

  // 联盟码海报
  getCanvasimg: function (qrcode, name, cardInfo) {
    var that = this;
    let url = "https://static.711688.net.cn/upload/card/source/ua_1911051408175899450.png";
    wx.downloadFile({ //联盟码背景图
      url: url,
      success: function (res) {
        let canvasimg = res.tempFilePath;
        that.getAllianceCode(qrcode, name, cardInfo, canvasimg);
      }
    })
  },
  getAllianceCode: function (qrcode, name, cardInfo, canvasimg) {
    wx.showLoading({
      title: '生成中...',
      mask: true,
    });
    var that = this;
    if (qrcode) {
      wx.downloadFile({
        url: qrcode,
        success: function (res) {
          wx.hideLoading();
          if (res.statusCode === 200) {
            var codeSrc = res.tempFilePath;
            that.sharePoste(name, cardInfo, canvasimg, codeSrc);
          } else {
            wx.showToast({
              title: '二维码下载失败！',
              icon: 'none',
              duration: 2000,
              success: function () {
                var codeSrc = "";
                that.sharePoste(name, cardInfo, canvasimg, codeSrc);
              }
            })
          }
        }
      })
    } else {
      var codeSrc = "";
      that.sharePoste(name, cardInfo, canvasimgbg, codeSrc);
    }
  },
  sharePoste: function (name, cardInfo, canvasimg, codeSrc) {
    wx.showLoading({
      title: '生成中...',
      mask: true,
    })
    var that = this;
    const ctx = wx.createCanvasContext('myCanvas');
    wx.createSelectorQuery().select('#canvas-container').boundingClientRect(function (rect) {
      var height = rect.height;
      var width = rect.width;

      // 绘制背景图
      ctx.drawImage(canvasimg, 0, 0, width, height);

      // 公司名
      if (cardInfo.Company) {
        ctx.setTextAlign('center');
        ctx.font = "18px sans-serif";
        ctx.fillStyle = 'rgba(120, 120, 120, 1)';
        ctx.fillText(cardInfo.Company, width / 2, height * 80 / 450, 280);
      }

      if (name) {
        // 联盟名
        ctx.setTextAlign('center');
        ctx.font = "18px sans-serif";
        ctx.fillStyle = 'rgba(251, 172, 38, 1)';
        ctx.fillText(name, width / 2, height * 150 / 450, 280);
      }

      // 绘制二维码
      if (codeSrc) {
        ctx.drawImage(codeSrc, width / 2 - width * 190 / 628, height * 172 / 450, width * 190 / 314, width * 190 / 314);
      }

      ctx.setTextAlign('center');
      ctx.font = "12px sans-serif";
      ctx.fillStyle = 'rgba(120, 120, 120, 1)';
      ctx.fillText('企动 · 玖玖客', width / 2, width * 397 / 314, 280);

    }).exec()

    setTimeout(function () {
      ctx.draw();
      wx.hideLoading();
    }, 1000)
  },
  savePost: function () {
    var that = this;
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'myCanvas',
        success: function (res) {
          wx.hideLoading();
          var tempFilePath = res.tempFilePath;
          wx.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success(res) {
              wx.showModal({
                content: '图片已保存到相册，赶紧晒一下吧~',
                showCancel: false,
                confirmText: '好的',
                confirmColor: '#333',
                success: function (res) {
                  if (res.confirm) { }
                },
                fail: function (res) { }
              })
            },
            fail: function (res) {
              wx.showToast({
                title: '请删掉小程序再重新授权允许保存至相册',
                icon: 'none',
                duration: 2000,
                mask: true
              })
            }
          })
        }
      });
    }, 1000);
  },
  // 圆形图片
  circleImg: function (ctx, img, x, y, r) {
    ctx.save();
    ctx.beginPath();
    var d = 2 * r;
    var cx = x + r;
    var cy = y + r;
    ctx.arc(cx, cy, r, 0, 2 * Math.PI, false);
    ctx.clip();
    ctx.drawImage(img, x, y, d, d);
    ctx.restore();
  },

  painter: function (canasId, data) {
    var ctx = wx.createCanvasContext(canasId);
    var bg_url = data.bg_url;
    return new Promise((resolve, reject) => {
      wx.downloadFile({
        url: bg_url,
        success: res => {
          if (res.statusCode === 200) {
            ctx.beginPath();
            ctx.drawImage(res.tempFilePath, 0, 0, 300, 200); // 大图
            ctx.draw(true, () => {
              wx.canvasToTempFilePath({
                canvasId: canasId,
                success: res => {
                  resolve(res.tempFilePath)
                },
                fail: err => {
                  reject(err)
                }
              })
            })
          }
        }
      })
    })
  },
  // 获取地理位置  
  getLocation: function () {
    let that = this;
    utils.getLocation(()=>{
     that.getAllianceStaffList(that.data.allianceid);
    },app);   
  },
})